<?php
/**
 * Created by gumaor.com
 * User: tommy
 */

namespace app\v1\controller;


use business\album\AlbumSaver;
use lib\Format;
use model\album\AlbumModel;
use model\user\UserModel;
use Timo\Core\Application;
use Timo\Core\Request;

class Album extends Base
{
    /**
     * 专辑列表
     *
     * @return array|string
     */
    public function find()
    {
        $p = Request::get('p', 1, 'intval');

        $page = ['p' => $p, 'limit' => 3];

        //专辑
        $albumModel = new AlbumModel();
        $albums = $albumModel
            ->fields('id, uid, title, cover, created')
            ->where(['status' => 1])
            ->order('id DESC')
            ->page($page)
            ->select();

        if (!empty($albums)) {
            //用户信息
            $uid_arr = array_unique(array_column($albums, 'uid'));
            $userModel = new UserModel();
            $users = $userModel
                ->fields('id, name, avatar')
                ->where(['id' => ['in', $uid_arr]])
                ->select();
            $users_hash = Format::hash('id', '', $users);

            foreach ($albums as &$album) {
                $album['user'] = $users_hash[$album['uid']];
                $album['created'] = date('Y-m-d H:i', $album['created']);
            }
        }

        return Application::result(0, 'ok', [
            'albums' => $albums,
            'page' => $page
        ]);
    }

    /**
     * 专辑详情
     *
     * @return array|string
     */
    public function detail()
    {
        $id = Request::get('id', 0, 'intval');

        $albumModel = new AlbumModel();
        $album = $albumModel
            ->fields('id, uid, title, cover, status created, updated')
            ->where($id)
            ->row();
        if (empty($album)) {
            return Application::result(1, '专辑不存在');
        }

        //用户
        $userModel = new UserModel();
        $user = $userModel->get($album['uid'], 'nickname, avatar');

        $album['user'] = $user;
        $album['created'] = date('Y-m-d H:i', $album['created']);
        $album['updated'] = date('Y-m-d H:i', $album['updated']);

        return Application::result(0, 'ok', [
            'album' => $album
        ]);
    }

    /**
     * 发布/更新专辑
     *
     * @return array|string
     */
    public function save()
    {
        $albumSaver = new AlbumSaver();
        return Application::result(...$albumSaver->run());
    }

    /**
     * 删除
     *
     * @return array|string
     */
    public function del()
    {
        $id = Request::post('id', 0, 'intval');

        if ($id <= 0) {
            return Application::result(1, 'params error');
        }

        $albumModel = new AlbumModel();
        $ret = $albumModel->where($id)->update(['status' => -1, 'deleted' => NOW_TIME]); //逻辑删除
        //$albumModel->delete($id); //物理删除
        if ($ret === false) {
            return Application::result(1, '删除失败');
        }
        return Application::result(0, '删除成功');
    }
}
